package com.hsgene.message.controller;

import com.hsgene.common.util.basic.SimpleRegexUtils;
import com.hsgene.common.util.character.CharactersConstant;
import com.hsgene.common.util.exception.CommonErrorCode;
import com.hsgene.common.util.http.HttpUtil;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.MessageResponse;
import com.hsgene.message.domain.MessageInfo;
import com.hsgene.message.service.MessageService;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

/**
 * 短信控制层
 *
 * @Author: wangxuefeng@hsgene.com
 * @Description:
 * @Date: Created in 15:28 2018/6/25
 * @Modified By:
 */
@RestController
@RequestMapping("/message/send")
public class MessageController {
    /**
     * Log
     */
    private static Logger LOGGER = LogManager.getLogger(MessageController.class);

    @Value("${sms.url}")
    private String url;
    @Value("${sms.username}")
    private String un;
    @Value("${sms.password}")
    private String pwd;
    @Autowired
    private MessageService messageService;

    /**
     * 发送单条消息
     *
     * @return
     */
    @GetMapping
    public Object sendMessage(String msgContent, String phones) {
        try {
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setSendTime(new Date());
            messageInfo.setMsgContent(msgContent);
            //发送get请求获取发送结果
            String sendResult = sendGetRequest(msgContent, phones);
            messageInfo.setReceivePhone(phones);
            messageInfo.setSendResult(sendResult);
            //消息保存数据库
            messageService.insert(messageInfo);
            LOGGER.info("send message is success...");
            return ApiResult.succ(messageInfo);
        } catch (Exception e) {
            LOGGER.error("encode msg is error", e);
            return ApiResult.fail(MessageResponse.SEND_MESSAGE_ERROR);
        }

    }

    @GetMapping("getVerifyCodeByPhone")
    public Object getVerifyCodeByPhone(String phone) {
        try {
            if (StringUtils.isBlank(phone) || !SimpleRegexUtils.isMobile(phone)) {
                return ApiResult.fail(CommonErrorCode.PHONE_INVALIDATION_FORMAT);
            }
            return messageService.getVerifyCodeByPhone(phone);
        } catch (Exception e) {
            LOGGER.error("get verify code is error", e);
            return ApiResult.fail(MessageResponse.GET_VERIFICATION_BY_PHONE_IS_ERROR);
        }
    }

    /**
     * 发送短信
     *
     * @param msgContent 短信内容
     * @param phones     手机号,可能有多个
     * @return
     * @throws UnsupportedEncodingException
     */
    private String sendGetRequest(String msgContent, String phones) throws UnsupportedEncodingException {
        msgContent = URLEncoder.encode(msgContent, "gb2312");
        String[] phoneArrays = StringUtils.split(phones, CharactersConstant.COMMA_EN);
        //GET发送短信
        StringBuilder builder = new StringBuilder();
        for (String mobile : phoneArrays) {
            String result = HttpUtil
                    .doGet(url + "?un=" + un + "&pwd=" + pwd + "&mobile=" + mobile + "&msg=" + msgContent);
            builder.append(result).append(CharactersConstant.COMMA_CH);
        }
        if (builder.length() > 0) {
            return builder.toString().substring(0, builder.length() - 1);
        }
        return builder.toString();
    }

}

